<template>
  <!-- 抖音商品 -->
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]" v-show="showSearch">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="活动ID" prop="activityId">
              <el-input v-model.trim="queryParams.activityId" placeholder="请输入" clearable style="width: 200px" />
            </el-form-item>
            <el-form-item label="店铺ID" prop="shopId">
              <el-input v-model.trim="queryParams.shopId" placeholder="请输入" clearable style="width: 200px" />
            </el-form-item>
            <el-form-item label="商品名称" prop="name">
              <el-input v-model.trim="queryParams.name" placeholder="请输入" clearable style="width: 200px" />
            </el-form-item>
            <el-form-item label="上下架" prop="enable">
              <el-select v-model="queryParams.enable" placeholder="请选择" clearable style="width: 90px">
                <el-option label="上架" :value="1" />
                <el-option label="下架" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item label="时间范围" prop="timeList">
              <el-date-picker v-model="timeList" type="daterange" range-separator="-" start-placeholder="开始时间"
                end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :default-time="defaultTime"
                style="width: 230px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery" icon="Search"
                v-hasPermi="['gms:tiktokGoods:query']">搜索</el-button>
              <el-button @click="resetQuery" icon="Refresh">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="hover">
      <!-- 功能按钮 -->
      <template #header>
        <el-row :gutter="10">
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"
            :search="true"></right-toolbar>
        </el-row>
      </template>
      <!-- 表格 -->
      <el-table v-loading="loading" :data="tiktokList" @sort-change="sortTableFun" max-height="550" border>
        <!-- <el-table-column label="ID" prop="id" align="center" width="175" /> -->
        <el-table-column label="商品" align="center" width="250" v-if="columns[0].visible">
          <template #default="scope">
            <div class="lioneuo">
              <el-row>
                <el-col :span="7" class="cuionseti">ID：</el-col>
                <el-col :span="17">{{ scope.row.id }}</el-col>
              </el-row>
              <el-row>
                <el-col :span="7" class="cuionseti">三方ID：</el-col>
                <el-col :span="17">{{ scope.row.goodsId }}</el-col>
              </el-row>
              <el-row>
                <el-col :span="7" class="cuionseti">名称：</el-col>
                <el-col :span="17">{{ scope.row.name }}</el-col>
              </el-row>
              <el-row>
                <el-col :span="7" class="cuionseti">销量：</el-col>
                <el-col :span="17">{{ scope.row.saleCount }}</el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="封面图片" prop="cover" align="center" width="120" v-if="columns[1].visible">
          <template #default="scope">
            <el-image style="width: 80px; height: 80px"
              :src="scope.row.cover "
              :preview-src-list="[scope.row.cover]" fit="contain" :preview-teleported="true" />
          </template>
        </el-table-column>
        <el-table-column label="素材封面" prop="materialCover" align="center" width="120" v-if="columns[2].visible">
          <template #default="scope">
            <el-image style="width: 80px; height: 80px"
              :src="scope.row.materialCover "
              :preview-src-list="[scope.row.materialCover]" fit="contain" :preview-teleported="true">
              <template #error>
                <div></div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="店铺" align="center" width="200" v-if="columns[3].visible">
          <template #default="scope">
            <div class="lioneuo">
              <el-row>
                <el-col :span="7" class="cuionseti">ID：</el-col>
                <el-col :span="17">{{ scope.row.shopId }}</el-col>
              </el-row>
              <el-row>
                <el-col :span="7" class="cuionseti">名称：</el-col>
                <el-col :span="17">{{ scope.row.shopName }}</el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="活动" align="center" width="150" v-if="columns[4].visible">
          <template #default="scope">
            <div class="lioneuo">
              <el-row>
                <el-col :span="8" class="cuionseti">ID：</el-col>
                <el-col :span="16">{{ scope.row.activityId }}</el-col>
              </el-row>
              <el-row>
                <el-col :span="8" class="cuionseti">名称：</el-col>
                <el-col :span="16">{{ scope.row.activityTitle }}</el-col>
              </el-row>
              <el-row>
                <el-col :span="8" class="cuionseti">团长：</el-col>
                <el-col :span="16">{{ scope.row.account }}</el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="活动时间" align="center" width="130" v-if="columns[5].visible">
          <template #default="scope">
            <div class="lioneuo">
              <el-row>
                <el-col :span="5" class="cuionseti">起：</el-col>
                <el-col :span="19">{{ scope.row.promoteStartDate }}</el-col>
              </el-row>
              <el-row>
                <el-col :span="5" class="cuionseti">止：</el-col>
                <el-col :span="19">{{ scope.row.promoteEndDate }}</el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="价格" prop="price" sortable="custom" align="center" width="90" v-if="columns[6].visible">
          <template #default="scope">￥{{ scope.row.price }}</template>
        </el-table-column>
        <el-table-column label="佣金比率" prop="commissionRate" sortable="custom" align="center" width="110"
          v-if="columns[7].visible">
          <template #default="scope">{{ scope.row.commissionRate }}%</template>
        </el-table-column>
        <el-table-column label="预估佣金" prop="estimatedCommissionFee" sortable="custom" align="center" width="110"
          v-if="columns[8].visible">
          <template #default="scope">￥{{ scope.row.estimatedCommissionFee }}</template>
        </el-table-column>
        <el-table-column label="服务费比率" prop="serviceRate" sortable="custom" align="center" width="120"
          v-if="columns[9].visible">
          <template #default="scope">{{ scope.row.serviceRate }}%</template>
        </el-table-column>
        <el-table-column label="预估服务费" prop="estimatedServiceFee" sortable="custom" align="center" width="120"
          v-if="columns[10].visible">
          <template #default="scope">￥{{ scope.row.estimatedServiceFee }}</template>
        </el-table-column>
        <el-table-column label="审核状态" prop="auditStatus" align="center" width="100" v-if="columns[11].visible">
          <template #default="scope">{{ auditStatusFilters(scope.row.auditStatus) }}</template>
        </el-table-column>
        <el-table-column label="类目名称" prop="categoryName" align="center" width="100" v-if="columns[12].visible" />
        <el-table-column fixed="right" label="上架状态" prop="enable" align="center" width="80" v-if="columns[13].visible">
          <template #default="scope">
            <el-switch v-model="scope.row.enable" :active-value="1" :inactive-value="0" @change="approve(scope.row)"
              :disabled="enableFlag"></el-switch>
          </template>
        </el-table-column>
        <!-- <el-table-column label="素材id" prop="materialId" align="center" /> -->
        <el-table-column fixed="right" label="操作" align="center" width="120">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleDetails(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip :content="scope.row.materialId ? '已绑定素材' : '未绑定素材'" placement="top">
              <el-button link type="primary" icon="Switch" @click="association(scope.row)"
                v-hasPermi="['gms:tiktokGoods:material']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['gms:tiktokGoods:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <el-dialog :title="dialog.title" v-model="dialog.visible" append-to-body width="90%">
      <!-- 搜索组合商品 -->
      <el-form ref="materialRef" :model="queryMaterial" :inline="true" label-width="100px">
        <el-form-item label="素材标题" prop="title">
          <el-input v-model.trim="queryMaterial.title" placeholder="请输入" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleMaterialQuery" icon="Search">搜索</el-button>
          <el-button @click="resetMaterialQuery" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 列表 -->
      <el-table v-loading="loadingmaterial" :data="materialList" max-height="550" border>
        <el-table-column label="封面" align="center" width="120">
          <template #default="scope">
            <el-image style="width: 80px; height: 80px"
              :src="scope.row.cover "
              :preview-src-list="[scope.row.cover]" fit="contain" :preview-teleported="true" />
          </template>
        </el-table-column>
        <el-table-column label="商品卖点" align="center" width="">
          <template #default="scope">{{ scope.row.sellingPoint }}</template>
        </el-table-column>
        <el-table-column label="素材标题" align="center" width="450">
          <template #default="scope">
            <el-tooltip class="box-item" effect="dark" :content="item" placement="top"
              v-for="(item, index) in scope.row.titles" :key="index">
              <div class="onseuoc">{{ item }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="口播台词" align="center" width="450">
          <template #default="scope">
            <el-tooltip class="box-item" effect="dark" :content="item" placement="top"
              v-for="(item, index) in scope.row.spokenLines" :key="index">
              <div class="onseuoc">{{ item }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort" width="60" />
        <el-table-column label="图片数量" align="center" prop="imageNum" width="80" />
        <el-table-column label="视频数量" align="center" prop="videoNum" width="80" />
        <el-table-column label="创建时间" fixed="right" align="center" width="150">
          <template #default="scope">{{ scope.row.createTime.slice(0, -3) }}</template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="100">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="materialDetails(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip content="绑定素材" placement="top">
              <el-button link type="primary" icon="TopRight" @click="binding(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination v-if="totalmaterial > 0" v-model:total="totalmaterial" v-model:page="queryMaterial.pageNum"
        v-model:limit="queryMaterial.pageSize" @pagination="getMaterial" />
      <el-dialog :title="dialogaterial.title" v-model="dialogaterial.visible" append-to-body width="56%">
        <detailsMaterial :id="materialId" flag="1" />
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script setup lang="ts" name="Tiktok">
import { MaterialQuery, MaterialVO } from '@/api/operates/material/types';
import { listMaterial } from '@/api/operates/material/index';
import { TiktokQuery, TiktokVO } from '@/api/operates/tiktok/types';
import { listTiktok, enableTiktok, delTiktok, materialTiktok } from '@/api/operates/tiktok/index';
import DetailsMaterial from "@/views/operates/material/subpage/detailsMaterial.vue";
import useUserStore from '@/store/modules/user';
const permissions = useUserStore().permissions;
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const id = ref<string | number>()
const loading = ref(true)
const showSearch = ref(true)
const enableFlag = ref(false)
const total = ref(0)
const timeList = ref<any>([])
const queryFormRef = ref<ElFormInstance>();
// 表格数据
const tiktokList = ref<TiktokVO[]>([]);
// 默认时间
const defaultTime = ref<[Date, Date]>([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
])
// 查询表单
const queryParams = ref<TiktokQuery>({
  pageNum: 1,
  pageSize: 10,
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const dialogaterial = reactive<DialogOption>({
  visible: false,
  title: ''
});
const materialId = ref<any>()
const loadingmaterial = ref(true)
const totalmaterial = ref(0)
const materialRef = ref<ElFormInstance>();
// 素材表格数据
const materialList = ref<MaterialVO[]>([]);
// 查询素材表单
const queryMaterial = ref<MaterialQuery>({
  type: 'GOODS',
  title: '',
  enable: 1,
  pageNum: 1,
  pageSize: 10,
});

const columns = ref<FieldOption[]>([
  { key: 0, label: `商品`, visible: true, children: [] },
  { key: 1, label: `封面图片`, visible: true, children: [] },
  { key: 2, label: `素材封面`, visible: true, children: [] },
  { key: 3, label: `店铺`, visible: true, children: [] },
  { key: 4, label: `活动`, visible: true, children: [] },
  { key: 5, label: `活动时间`, visible: true, children: [] },
  { key: 6, label: `价格`, visible: true, children: [] },
  { key: 7, label: `佣金比率`, visible: true, children: [] },
  { key: 8, label: `预估佣金`, visible: true, children: [] },
  { key: 9, label: `服务费比率`, visible: true, children: [] },
  { key: 10, label: `预估服务费`, visible: true, children: [] },
  { key: 11, label: `审核状态`, visible: true, children: [] },
  { key: 12, label: `类目名称`, visible: true, children: [] },
  { key: 13, label: `上架状态`, visible: true, children: [] },
])

/**
 * 查询商品列表
 */
const getList = async () => {
  loading.value = true
  const query = { ...queryParams.value }
  if (timeList.value.length) {
    query.startDate = timeList.value[0]
    query.endDate = timeList.value[1]
  }
  const res = await listTiktok(query);
  tiktokList.value = res.data.list;
  total.value = res.data.total;
  loading.value = false;
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/**
 * 重置搜索
 */
const resetQuery = () => {
  timeList.value = [];
  queryFormRef.value?.resetFields();
  handleQuery();
}

/**
 * 排序
 * @param event 
 */
const sortTableFun = (event: any) => {
  queryParams.value.orderByColumn = event.prop;
  if (event.order === null) {
    queryParams.value.isAsc = ''
  } else if (event.order === 'descending') {
    queryParams.value.isAsc = 'desc'
  } else if (event.order === 'ascending') {
    queryParams.value.isAsc = 'asc'
  }
  getList()
};

const auditStatusFilters = (val: number) => {
  if (val === 0) {
    return '待审核'
  } else if (val === 1) {
    return '审核通过'
  } else if (val === 2) {
    return '审核拒绝'
  } else if (val === 3) {
    return '重新报名'
  } else if (val === 4) {
    return '未知状态'
  } else if (val === 5) {
    return '商家取消'
  }
}

const enableFilters = (val: number) => {
  if (val === 0) {
    return '下架'
  } else if (val === 1) {
    return '上架'
  }
}

/**
 * 抖音商品详情
 * @param row 
 */
const handleDetails = (row: TiktokVO) => {
  // router.push({ path: `/tiktok/detail/${row.id}` });
  const id = row.id
  router.push({ path: `/tiktok/detail`, query: { id } });
}

/**
 * 审核(上架/下架)
 * @param row 
 */
const approve = async (row: TiktokVO) => {
  // ['gms:tiktokGoods:updown']
  try {
    if (row.materialId === 0) {
      proxy?.$modal.msgError('该商品未关联素材，不可上架');
      row.enable = row.enable === 1 ? 0 : 1;
      return false;
    }
    let text = row.enable === 1 ? "上架" : "下架";
    await enableTiktok(row.id);
    getList();
    proxy?.$modal.msgSuccess(text + "成功");
  } catch (error) {
    row.enable = row.enable === 1 ? 0 : 1;
  }
}

/**
 * 查询商品列表(素材)
 */
const getMaterial = async () => {
  loadingmaterial.value = true
  const query = { ...queryMaterial.value }
  const res = await listMaterial(query);
  materialList.value = res.data.list;
  totalmaterial.value = res.data.total;
  loadingmaterial.value = false;
}

const joint = async (materialId: number) => {
  try {
    const query = { id: id.value, materialId: materialId }
    // console.log(query);
    await materialTiktok(query)
    getList();
  } catch (error) { }
}

/**
 * 素材对话框或解绑素材
 * @param row 
 */
const association = async (row: TiktokVO) => {
  try {
    const flag = row.materialId ? true : false;
    id.value = row.id;
    if (flag) {
      await proxy?.$modal.confirm('是否确认解绑素材');
      joint(0)
      proxy?.$modal.msgSuccess("解绑成功");
    } else {
      dialog.visible = true;
      dialog.title = "添加素材";
      getMaterial()
    }
  } catch (error) { }
}

const binding = (materialId: number) => {
  joint(materialId)
  proxy?.$modal.msgSuccess("绑定成功");
  materialRef.value?.resetFields();
  dialog.visible = false;
}

const materialDetails = (id: number) => {
  materialId.value = id
  dialogaterial.visible = true;
  dialogaterial.title = "";
}

/**
 * 搜索按钮操作(素材)
 */
const handleMaterialQuery = () => {
  queryMaterial.value.pageNum = 1;
  getMaterial();
}

/**
 * 重置搜索(素材)
 */
const resetMaterialQuery = () => {
  materialRef.value?.resetFields();
  handleMaterialQuery();
}

/**
 * 商品删除
 * @param row 
 */
const handleDelete = async (row: TiktokVO) => {
  try {
    if (row.enable == 1) {
      proxy?.$modal.msgError('请先执行禁用操作');
      return
    }
    await proxy?.$modal.confirm('是否确认删除商品');
    await delTiktok(row.id);
    getList();
    proxy?.$modal.msgSuccess('删除成功');
  } catch (error) { }
}

const enableFn = () => {
  // '*:*:*'
  // enableFlag
  if (permissions[0] !== '*:*:*') {
    enableFlag.value = !permissions.includes('gms:tiktokGoods:updown')
  }
}

onMounted(() => {
  enableFn();
  getList();
});
</script>

<style scoped>
.onseuoc {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  background-color: #409eff;
  color: #fff;
  border-radius: 20px;
  padding-left: 13px;
  margin-bottom: 10px;
  cursor: pointer;
  text-align: left;
}
</style>